<template>
  <div class="top-nav">
    <div class="top-nav-container">
      <!-- 使用 img 标签显示图片 logo -->
      <div class="logo" @click="goToHome">
        <img src="/images/backgroundImages/logo.png" alt="二次元头条" style="height: 50px;">
      </div>

      <div class="nav-items">
        <div
            v-for="category in displayedCategories"
            :key="category.id"
            :class="['nav-item', { active: activeCategory === category.id }]"
            @click="setActiveCategory(category.id)"
        >
          {{ category.name }}
        </div>
        <el-dropdown v-if="hasMoreCategories" @command="handleMoreCategory">
          <div class="nav-item more">
            更多
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="category in moreCategories"
                :key="category.id"
                :command="category.id"
              >
                {{ category.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="user-actions">
        <template v-if="userStore.token">
          <el-dropdown @command="handleMessageCommand">
            <div class="action-button">
              <el-badge :value="unreadMessageCount > 0 ? unreadMessageCount : ''" :hidden="!unreadMessageCount" class="message-badge">
                <el-icon><Message /></el-icon>
              </el-badge>
              <span>消息</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="system">
                  系统通知
                  <el-badge v-if="systemMessageCount > 0" :value="systemMessageCount" class="item" />
                </el-dropdown-item>
                <el-dropdown-item command="comment">
                  评论消息
                  <el-badge v-if="commentMessageCount > 0" :value="commentMessageCount" class="item" />
                </el-dropdown-item>
                <el-dropdown-item command="like">
                  点赞消息
                  <el-badge v-if="likeMessageCount > 0" :value="likeMessageCount" class="item" />
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-dropdown @command="handlePublishCommand">
            <div class="action-button">
              <el-icon><Edit /></el-icon>
              <span>发布</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="news">发布新闻</el-dropdown-item>
<!--                <el-dropdown-item command="article">发布文章</el-dropdown-item>-->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar
                :size="32"
                :src="userStore.userInfo.avatar || doro"
              />
              <span class="username">{{ userStore.userInfo.username }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="draft">我的草稿</el-dropdown-item>
                <el-dropdown-item v-if="isAdmin" command="review">新闻审核</el-dropdown-item>
                <el-dropdown-item command="feedback">反馈问题</el-dropdown-item>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <el-button v-else type="primary" size="small" @click="showLoginDialog">登录/注册</el-button>
      </div>
    </div>
     <!-- 意见反馈弹窗 -->
    <FeedbackDialog ref="feedbackDialogRef" />
    <!-- 登录弹框 -->
    <LoginDialog ref="loginDialogRef" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { ArrowDown, Message, Edit } from '@element-plus/icons-vue'
import axios from 'axios'
import FeedbackDialog from '/src/views/FeedbackDialog.vue'
import LoginDialog from '@/components/LoginDialog.vue'
import doro from '/public/images/doro.jpg'

const router = useRouter()
const userStore = useUserStore()
const feedbackDialogRef = ref()
const loginDialogRef = ref()

// 添加消息相关的响应式数据
const unreadMessageCount = ref(0)
const commentMessageCount = ref(0)
const likeMessageCount = ref(0)
const systemMessageCount = ref(0)

// 分类数据
const categories = ref([
  {id: 1, name: '头条推荐'},
  {id: 2, name: '热点新闻'},
  {id: 3, name: '研发.编程'},
  {id: 4, name: '虚拟.现实'},
  {id: 5, name: '产品.运营'},
  {id: 6, name: '视觉.创意'},
  {id: 7, name: '职场.考级'}
])

// 显示前5个分类
const displayedCategories = computed(() => {
  return categories.value.slice(0, 5)
})

// 剩余的分类
const moreCategories = computed(() => {
  return categories.value.slice(5)
})

// 是否有更多分类
const hasMoreCategories = computed(() => {
  return categories.value.length > 5
})

// 判断是否为管理员
const isAdmin = computed(() => {
  return userStore.userInfo.userType !== 1
})

const activeCategory = ref(1)

// 设置当前分类
const setActiveCategory = (id) => {
  activeCategory.value = id
  // 直接触发路由变化
  if (router.currentRoute.value.name === 'Home') {
    router.replace({
      query: {
        ...router.currentRoute.value.query,
        category: id
      }
    })
  } else {
    router.push({
      name: 'Home',
      query: { category: id }
    })
  }
  emit('category-change', id)
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/personalCenter')
      break
    case 'draft':
      router.push('/draft/management')
      break
    case 'review':
      window.open('http://localhost:5173/login','blank')
      break
    case 'feedback':
    feedbackDialogRef.value.openDialog()
    break
    case 'logout':
      userStore.logout()
        router.push('/')
      ElMessage.success('已退出登录')
      break
  }
}

// 显示登录弹框
const showLoginDialog = () => {
  loginDialogRef.value.show()
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await axios.get('/app/categories')
    categories.value = response.data.data.map(category => ({
      id: category.id,
      name: category.name
    }))
    if (categories.value.length > 0) {
      activeCategory.value = categories.value[0].id
      emit('category-change', categories.value[0].id)
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 处理更多分类的点击
const handleMoreCategory = (categoryId) => {
  setActiveCategory(categoryId)
}

// 处理消息下拉菜单命令
const handleMessageCommand = (command) => {
  switch (command) {
    case 'system':
      router.push('/messages/system')
      break
    case 'comment':
      router.push('/messages/comment')
      break
    case 'like':
      router.push('/messages/likes')
      break
  }
}

// 处理发布下拉菜单命令
const handlePublishCommand = (command) => {
  switch (command) {
    case 'news':
      router.push('/publish/news')
      break
    case 'article':
      router.push('/publish/article')
      break
  }
}

// 获取未读消息数量和消息列表
const fetchMessages = async () => {
  if (!userStore.token) return

  try {
    // 获取未读消息数量
    const countResponse = await axios.get('/app/message/unreadCount',{
      params: {
        userId: userStore.userInfo.id
      }
    })
    if (countResponse.data.code === 200) {
      const messageData = countResponse.data.data
      unreadMessageCount.value = messageData.unreadCount
      commentMessageCount.value = messageData.commentMessageCount
      likeMessageCount.value = messageData.likeMessageCount
      systemMessageCount.value = messageData.systemMessageCount
    }
  } catch (error) {
    console.error('获取消息失败:', error)
  }
}

// 监听用户登录状态变化
watch(() => userStore.token, (newToken) => {
  if (newToken) {
    fetchMessages()
  } else {
    unreadMessageCount.value = 0
    commentMessageCount.value = 0
    likeMessageCount.value = 0
    systemMessageCount.value = 0
  }
})

// 定义emit
const emit = defineEmits(['category-change', 'show-login'])

// 跳转到首页
const goToHome = () => {
  router.push({ name: 'Home' })
}

onMounted(() => {
  fetchCategories()
  if (userStore.token) {
    fetchMessages()
  }
})
</script>

<style scoped>
.top-nav {
  background-color: #64CBFF;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  position: sticky;
  top: 0;
  z-index: 100;
}

.top-nav-container {
  max-width: 1500px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 60px;
}

.logo {
  font-size: 26px;
  font-weight: bold;
  color: white;
  margin-right: 40px;
  cursor: pointer;
}

.nav-items {
  display: flex;
  flex: 1;
}

.nav-item {
  padding: 0 15px;
  height: 60px;
  line-height: 60px;
  font-size: 16px;
  cursor: pointer;
  position: relative;
  color: #4a4a4a;
  border: none;
  outline: none;
}

.nav-item:hover {
  color: white;
  border: none;
  outline: none;
}

.nav-item:focus {
  border: none;
  outline: none;
}

.nav-item.active {
  color: white;
  font-weight: bold;
}

.nav-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 15px;
  right: 15px;
  height: 3px;
  background-color: white;
}

.nav-item.more {
  display: flex;
  align-items: center;
  gap: 4px;
  border: none;
  outline: none;
}

.nav-item.more:hover {
  border: none;
  outline: none;
}

.nav-item.more:focus {
  border: none;
  outline: none;
}

.nav-item.more .el-icon {
  font-size: 12px;
  margin-left: 2px;
}

.user-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 20px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  color: #4a4a4a;
  font-size: 14px;
  padding: 0 8px;
  height: 32px;
  line-height: 32px;
  border: none;
  outline: none;
}

.action-button:hover {
  color: white;
  border: none;
  outline: none;
}

.action-button:focus {
  border: none;
  outline: none;
}

.action-button .el-icon {
  font-size: 18px;
}

.message-badge :deep(.el-badge__content) {
  background-color: #f85959;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
  height: 32px;
  line-height: 32px;
  border: none;
  outline: none;
}

.user-info:hover {
  border: none;
  outline: none;
}

.user-info:focus {
  border: none;
  outline: none;
}

.user-info .username {
  margin-left: 8px;
  font-size: 14px;
  color: #333;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .el-badge {
    margin-left: 8px;
  }

  .el-badge__content {
    background-color: #f85959;
    border: none;
  }
}

:deep(.el-dropdown-menu__item:hover) {
  color: #f85959;
  background-color: #fff5f5;
}

:deep(.el-dropdown__popper) {
  border: none !important;
}

:deep(.el-dropdown-menu) {
  border: none !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

:deep(.el-dropdown-menu__item:focus) {
  background-color: #fff5f5;
  color: #f85959;
  border: none;
  outline: none;
}
</style>